import React, { useState, useEffect, memo } from "react";
import { useTranslation } from "react-i18next";
import "./index.css";

type Props = {
  simple?: boolean;
};

const LanguageSwitcher: React.FC<Props> = memo(({ simple = false }) => {
  const { i18n, t } = useTranslation("nav");
  const [isOpen, setIsOpen] = useState(false);
  const transferLanguage = (lang: string) => (lang === "zh" ? "简体中文" : "English");
  const [currentLanguage, setCurrentLanguage] = useState(transferLanguage(i18n.language));

  useEffect(() => {
    const handleLanguageChange = (lng: string) => {
      setCurrentLanguage(transferLanguage(lng));
    };

    i18n.on("languageChanged", handleLanguageChange);
    return () => {
      i18n.off("languageChanged", handleLanguageChange);
    };
  }, [i18n]);

  const changeLanguage = (lng: string) => {
    i18n.changeLanguage(lng);
    localStorage.setItem("i18nextLng", lng); // 保存语言设置到本地存储
    setIsOpen(false);
  };

  return (
    <div className="language-switcher">
      {simple ? (
        <div className="lang-btn-simple" onClick={() => setIsOpen(true)}>
          {currentLanguage}
        </div>
      ) : (
        <div className="lang-btn" onClick={() => setIsOpen(true)}>
          <div className="icon"></div>
          <div className="text">{t("language")}</div>
          <div className="arrow"></div>
        </div>
      )}

      {isOpen && (
        <div className="lang-panel">
          <div className="list">
            <div className="title">{t("switchLanguage")}</div>
            <div className={`lang-item ${i18n.language === "zh" ? "active" : ""}`} onClick={() => changeLanguage("zh")}>
              中文
            </div>
            <div className={`lang-item ${i18n.language === "en" ? "active" : ""}`} onClick={() => changeLanguage("en")}>
              English
            </div>
          </div>
        </div>
      )}
    </div>
  );
});

export default LanguageSwitcher;
